package me.wenshan.demo.webdemo;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	
	public void destroy() {
		System.out.println("LoginFilter 删除");	
	}

	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/html;charset=utf-8");
		HttpSession session = ((HttpServletRequest) request).getSession(true);
		Object userVal = session.getAttribute("user");
		String path = ((HttpServletRequest) request).getRequestURI();
		
		if (userVal == null)
		{
			if (path.endsWith("index.html") || path.endsWith("LoginServlet"))
			{
				chain.doFilter(request, response);	
			}
			else
				((HttpServletResponse)response).sendRedirect("index.html");
		}
		else
		// pass the request along the filter chain
			chain.doFilter(request, response);
	}

	
	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("LoginFilter 初始化");
	}

}
